package com.bosssoft.ct.redis.demo1.contoller;

import com.bosssoft.ct.redis.demo1.model.User;
import com.bosssoft.ct.redis.demo1.service.UserService;
import com.bosssoft.ct.redis.demo1.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;

/**
 * @author ChenTong
 * @version 1.0
 * @description 用户管理逻辑控制
 * @date 2020/6/18 14:24
 * @modified
 **/
@Slf4j
@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisUtil redisUtil;

    private Random rand;



    @GetMapping("test")
    public List<User> test(){
        return userService.getAllUser();
    }

    @GetMapping("cacheAllUser")
    public String cacheAllUser(){
        // random 方便生成ttl
        try {
            this.rand = SecureRandom.getInstanceStrong();
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(),e);
        }
        List<User> users = userService.getAllUser();
        for (User user: users)
            // 对于每个数组随机生成有效时间
            redisUtil.set(rand.nextInt(1000),"user-"+user.getId(),user);
        return "success";
    }

    @GetMapping("getNotExist/{id}")
    public String getNotExist(@PathVariable("id") Long id){
        User user = redisUtil.get("user-"+id,User.class);
        if (null == user){
            user = new User();
            redisUtil.set(5*60,"user-empty",user);
        }
        return "success";
    }

    @GetMapping("getUser/{id}")
    public User getUserById(@PathVariable("id") Long id){
        return userService.getUserByIdRedis(id);
    }


}
